package com.hehe.boot.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hehe.boot.pojo.Drug;
import com.hehe.boot.pojo.Result;
import com.hehe.boot.pojo.User;
import com.hehe.boot.service.DrugService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/drug")
public class DrugController {

    @Autowired
    private DrugService drugService;

    @GetMapping("/list")
    public Result<List<Drug>> list(){
        return Result.success(drugService.list());
    }

    @GetMapping("/listFromRedis")
    public Result<Set<Drug>> ListFromRedis(){
        return Result.success(drugService.listFromRedis());
    }

    @GetMapping("redisRefill")
    public Result RedisRefill(){
        return Result.success(drugService.redisRefill());
    }

    @GetMapping("/detail")
    public Result<Drug> detail(@RequestParam Long id){
        return Result.success(drugService.getById(id));
    }

    @DeleteMapping("/{id}")
    public Result deleteDrug(@PathVariable Long id){
        Boolean flag = drugService.removeById(id);
        if (flag == false){
            return Result.error("DeleteDrug error: fail to delete reservation");
        }
        return Result.success();
    }

//    @GetMapping("/find")
//    public Result<List<Drug>> find(@RequestParam String query){
//        return Result.success(drugService.getDrugLike(query));
//    }

    @GetMapping("/find")
    public Result<IPage<Drug>> findall(@RequestParam(required = false) String query,
                                       @RequestParam Integer page){
        if (query != null && !query.isEmpty()) {
            return Result.success(drugService.getProPageLike(query,page));
        }
        return Result.success(drugService.getProPage(page));
    }

    @PostMapping("/insert")
    public Result<Boolean> insert(@RequestBody Drug drug){
        return Result.success(drugService.insertDrug(drug));
    }

    @PostMapping("/update")
    public Result update(@RequestBody Drug drug){
        return Result.success(drugService.updateDrug(drug));
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody Drug drug){
        return Result.success(drugService.deleteDrug(drug));
    }
}
